<template>
  <div class="dashboard">
    <!-- 页面标题 -->
    <div class="dashboard-header">
      <h1 class="page-title">仪表盘</h1>
      <p class="page-subtitle">欢迎回来，{{ authStore.user?.username }}！</p>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-grid">
      <n-card class="stat-card" hoverable>
        <div class="stat-content">
          <div class="stat-icon">
            <n-icon size="24" color="#18a058">
              <CircleCheck />
            </n-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ completedTodosCount }}</div>
            <div class="stat-label">已完成任务</div>
          </div>
        </div>
      </n-card>

      <n-card class="stat-card" hoverable>
        <div class="stat-content">
          <div class="stat-icon">
            <n-icon size="24" color="#f0a020">
              <Clock />
            </n-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ pendingTodosCount }}</div>
            <div class="stat-label">待办任务</div>
          </div>
        </div>
      </n-card>

      <n-card class="stat-card" hoverable>
        <div class="stat-content">
          <div class="stat-icon">
            <n-icon size="24" color="#2080f0">
              <Code />
            </n-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ algorithmsCount }}</div>
            <div class="stat-label">算法题目</div>
          </div>
        </div>
      </n-card>

      <n-card class="stat-card" hoverable>
        <div class="stat-content">
          <div class="stat-icon">
            <n-icon size="24" color="#d03050">
              <Calendar />
            </n-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ todayEventsCount }}</div>
            <div class="stat-label">今日事件</div>
          </div>
        </div>
      </n-card>
    </div>

    <!-- 主要内容区域 -->
    <div class="dashboard-content">
      <!-- 左侧：日历和事件 -->
      <div class="left-section">
        <!-- 日历组件 -->
        <n-card title="日历" class="calendar-card">
          <template #header-extra>
            <n-button 
              size="small" 
              type="primary" 
              @click="showEventModal = true"
            >
              <template #icon>
                <n-icon><Plus /></n-icon>
              </template>
              添加事件
            </n-button>
          </template>
          
          <div class="calendar-container">
            <n-date-picker
              v-model:value="selectedDate"
              type="date"
              panel
              :is-date-disabled="isDateDisabled"
              @update:value="handleDateSelect"
            />
          </div>
        </n-card>

        <!-- 今日事件 -->
        <n-card title="今日事件" class="events-card">
          <template #header-extra>
            <n-tag size="small" type="info">
              {{ todayEvents.length }} 个事件
            </n-tag>
          </template>
          
          <div class="events-list">
            <div 
              v-if="todayEvents.length === 0" 
              class="empty-state"
            >
              <n-empty description="今天没有安排事件" />
            </div>
            
            <div 
              v-for="event in todayEvents" 
              :key="event.id"
              class="event-item"
            >
              <div class="event-time">
                {{ event.time || '全天' }}
              </div>
              <div class="event-content">
                <div class="event-title">{{ event.title }}</div>
                <div v-if="event.description" class="event-description">
                  {{ event.description }}
                </div>
              </div>
              <div class="event-actions">
                <n-button 
                  size="tiny" 
                  quaternary 
                  @click="editEvent(event)"
                >
                  <template #icon>
                    <n-icon><Edit /></n-icon>
                  </template>
                </n-button>
                <n-button 
                  size="tiny" 
                  quaternary 
                  type="error"
                  @click="deleteEvent(Number(event.id))"
                >
                  <template #icon>
                    <n-icon><Trash /></n-icon>
                  </template>
                </n-button>
              </div>
            </div>
          </div>
        </n-card>
      </div>

      <!-- 右侧：待办事项 -->
      <div class="right-section">
        <!-- 快速添加任务 -->
        <n-card title="快速添加任务" class="quick-add-card">
          <div class="quick-add-form">
            <n-input
              v-model:value="newTodoTitle"
              placeholder="输入任务标题..."
              @keydown.enter="handleQuickAddTodo"
            >
              <template #suffix>
                <n-button 
                  size="small" 
                  type="primary" 
                  :disabled="!newTodoTitle.trim()"
                  @click="handleQuickAddTodo"
                >
                  添加
                </n-button>
              </template>
            </n-input>
          </div>
        </n-card>

        <!-- 待办事项列表 -->
        <n-card title="最近任务" class="todos-card">
          <template #header-extra>
            <n-button 
              size="small" 
              text 
              @click="$router.push('/todos')"
            >
              查看全部
            </n-button>
          </template>
          
          <div class="todos-list">
            <div 
              v-if="recentTodos.length === 0" 
              class="empty-state"
            >
              <n-empty description="暂无待办任务" />
            </div>
            
            <div 
              v-for="todo in recentTodos" 
              :key="todo.id"
              class="todo-item"
              :class="{ completed: todo.completed }"
            >
              <n-checkbox
                :checked="todo.completed"
                @update:checked="toggleTodo(todo.id)"
              />
              <div class="todo-content">
                <div class="todo-title">{{ todo.title }}</div>
                <div v-if="todo.dueDate" class="todo-due-date">
                  <n-icon size="12"><Clock /></n-icon>
                  {{ formatDate(todo.dueDate, 'MM-DD HH:mm') }}
                </div>
              </div>
              <div class="todo-priority">
                <n-tag 
                  v-if="todo.priority > 0"
                  size="small"
                  :type="getPriorityType(todo.priority)"
                >
                  {{ getPriorityText(todo.priority) }}
                </n-tag>
              </div>
            </div>
          </div>
        </n-card>

        <!-- 即将到期的任务 -->
        <n-card title="即将到期" class="upcoming-card">
          <div class="upcoming-list">
            <div 
              v-if="upcomingTodos.length === 0" 
              class="empty-state"
            >
              <n-empty description="暂无即将到期的任务" size="small" />
            </div>
            
            <div 
              v-for="todo in upcomingTodos" 
              :key="todo.id"
              class="upcoming-item"
            >
              <div class="upcoming-content">
                <div class="upcoming-title">{{ todo.title }}</div>
                <div class="upcoming-date">
                  {{ formatRelativeTime(todo.dueDate!) }}
                </div>
              </div>
              <n-tag 
                size="small"
                :type="getUrgencyType(todo.dueDate!)"
              >
                {{ getUrgencyText(todo.dueDate!) }}
              </n-tag>
            </div>
          </div>
        </n-card>
      </div>
    </div>

    <!-- 事件编辑模态框 -->
    <n-modal v-model:show="showEventModal" preset="card" title="添加事件" style="width: 500px">
      <n-form
        ref="eventFormRef"
        :model="eventForm"
        :rules="eventRules"
        label-placement="top"
      >
        <n-form-item path="title" label="事件标题">
          <n-input v-model:value="eventForm.title" placeholder="请输入事件标题" />
        </n-form-item>
        
        <n-form-item path="date" label="日期">
          <n-date-picker 
            v-model:value="eventForm.date" 
            type="date" 
            style="width: 100%"
          />
        </n-form-item>
        
        <n-form-item path="time" label="时间（可选）">
          <n-time-picker 
            v-model:value="eventForm.time" 
            format="HH:mm"
            style="width: 100%"
          />
        </n-form-item>
        
        <n-form-item path="description" label="描述（可选）">
          <n-input 
            v-model:value="eventForm.description" 
            type="textarea" 
            placeholder="请输入事件描述"
            :rows="3"
          />
        </n-form-item>
        
        <n-form-item path="color" label="颜色">
          <div class="color-picker">
            <div 
              v-for="color in eventColors" 
              :key="color"
              class="color-option"
              :class="{ active: eventForm.color === color }"
              :style="{ backgroundColor: color }"
              @click="eventForm.color = color"
            ></div>
          </div>
        </n-form-item>
      </n-form>
      
      <template #footer>
        <div class="modal-footer">
          <n-button @click="showEventModal = false">取消</n-button>
          <n-button 
            type="primary" 
            :loading="calendarStore.isLoading"
            @click="handleSaveEvent"
          >
            保存
          </n-button>
        </div>
      </template>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
// import { useRouter } from 'vue-router'
import {
  NCard,
  NIcon,
  NButton,
  NTag,
  NDatePicker,
  NTimePicker,
  NEmpty,
  NCheckbox,
  NInput,
  NModal,
  NForm,
  NFormItem,
  useMessage,
  type FormInst,
  type FormRules
} from 'naive-ui'
import {
  CircleCheck,
  Clock,
  Code,
  Calendar,
  Plus,
  Edit,
  Trash
} from '@vicons/tabler'
import { useAuthStore } from '@/stores/auth'
import { useTodosStore } from '@/stores/todos'
import { useAlgorithmsStore } from '@/stores/algorithms'
import { useCalendarStore } from '@/stores/calendar'
import { formatDate, formatRelativeTime, getPriorityText } from '@/utils'
import type { CalendarEvent, CreateEventRequest } from '@/types/calendar'

// const router = useRouter()
const message = useMessage()
const authStore = useAuthStore()
const todosStore = useTodosStore()
const algorithmsStore = useAlgorithmsStore()
const calendarStore = useCalendarStore()

// 表单引用
const eventFormRef = ref<FormInst | null>(null)

// 选中的日期
const selectedDate = ref<number>(Date.now())

// 快速添加任务
const newTodoTitle = ref('')

// 事件模态框
const showEventModal = ref(false)
const eventForm = ref<{
  title: string
  date: number | null
  time: number | null
  description: string
  color: string
}>({
  title: '',
  date: Date.now(),
  time: null,
  description: '',
  color: '#2080f0'
})

// 事件颜色选项
const eventColors = [
  '#2080f0', '#18a058', '#f0a020', '#d03050',
  '#722ed1', '#eb2f96', '#13c2c2', '#52c41a'
]

// 事件表单验证规则
const eventRules: FormRules = {
  title: [
    {
      required: true,
      message: '请输入事件标题',
      trigger: ['input', 'blur']
    }
  ],
  date: [
    {
      required: true,
      message: '请选择日期',
      trigger: ['change', 'blur']
    }
  ]
}

// 计算属性
const completedTodosCount = computed(() => {
  return todosStore.completedTodos.length
})

const pendingTodosCount = computed(() => {
  return todosStore.pendingTodos.length
})

const algorithmsCount = computed(() => {
  return algorithmsStore.problems.length
})

const todayEventsCount = computed(() => {
  return calendarStore.todayEvents.length
})

const todayEvents = computed(() => {
  return calendarStore.todayEvents
})

const recentTodos = computed(() => {
  return todosStore.todos.slice(0, 8)
})

const upcomingTodos = computed(() => {
  return todosStore.upcomingTodos.slice(0, 5)
})

// 获取优先级类型
const getPriorityType = (priority: number): 'default' | 'success' | 'warning' | 'error' => {
  const types: ('default' | 'success' | 'warning' | 'error')[] = ['default', 'success', 'warning', 'error']
  return types[priority] || 'default'
}

// 获取紧急程度类型
const getUrgencyType = (dueDate: Date) => {
  const now = new Date()
  const due = new Date(dueDate)
  const diff = due.getTime() - now.getTime()
  const hours = diff / (1000 * 60 * 60)
  
  if (hours < 24) return 'error'
  if (hours < 72) return 'warning'
  return 'info'
}

// 获取紧急程度文本
const getUrgencyText = (dueDate: Date) => {
  const now = new Date()
  const due = new Date(dueDate)
  const diff = due.getTime() - now.getTime()
  const hours = diff / (1000 * 60 * 60)
  
  if (hours < 24) return '紧急'
  if (hours < 72) return '即将到期'
  return '正常'
}

// 检查日期是否禁用
const isDateDisabled = (_date: number) => {
  // 可以在这里添加禁用日期的逻辑
  return false
}

// 处理日期选择
const handleDateSelect = (date: number | null) => {
  if (date) {
    calendarStore.setSelectedDate(new Date(date).toISOString().split('T')[0])
  }
}

// 快速添加待办事项
const handleQuickAddTodo = async () => {
  if (!newTodoTitle.value.trim()) return
  
  try {
    // 获取默认列表ID（第一个列表）
    const defaultListId = todosStore.todoLists[0]?.id
    if (!defaultListId) {
      message.error('请先创建一个待办事项列表')
      return
    }
    
    await todosStore.createTodo({
      title: newTodoTitle.value.trim(),
      listId: defaultListId
    })
    
    newTodoTitle.value = ''
    message.success('任务添加成功')
    
    // 记录活动
    await calendarStore.recordActivity({ date: new Date().toISOString().split('T')[0], count: 1 })
  } catch (error) {
    message.error('添加任务失败')
  }
}

// 切换待办事项状态
const toggleTodo = async (todoId: number) => {
  try {
    await todosStore.toggleTodo(todoId)
    
    // 记录活动
    await calendarStore.recordActivity({ date: new Date().toISOString().split('T')[0], count: 1 })
  } catch (error) {
    message.error('操作失败')
  }
}

// 编辑事件
const editEvent = (event: CalendarEvent) => {
  eventForm.value = {
    title: event.title,
    date: new Date(event.date).getTime(),
    time: event.time ? new Date(`1970-01-01T${event.time}`).getTime() : null,
    description: event.description || '',
    color: event.color || '#2080f0'
  }
  showEventModal.value = true
}

// 删除事件
const deleteEvent = async (eventId: number) => {
  try {
    await calendarStore.deleteEvent(eventId)
    message.success('事件删除成功')
  } catch (error) {
    message.error('删除事件失败')
  }
}

// 保存事件
const handleSaveEvent = async () => {
  if (!eventFormRef.value) return
  
  try {
    await eventFormRef.value.validate()
    
    const eventData: CreateEventRequest = {
      title: eventForm.value.title,
      date: new Date(eventForm.value.date!),
      time: eventForm.value.time ? new Date(eventForm.value.time).toTimeString().slice(0, 5) : undefined,
      description: eventForm.value.description || undefined,
      color: eventForm.value.color
    }
    
    await calendarStore.createEvent(eventData)
    
    showEventModal.value = false
    message.success('事件创建成功')
    
    // 重置表单
    eventForm.value = {
      title: '',
      date: Date.now(),
      time: null,
      description: '',
      color: '#2080f0'
    }
    
    // 记录活动
    await calendarStore.recordActivity({ date: new Date().toISOString().split('T')[0], count: 1 })
  } catch (error) {
    console.error('Save event failed:', error)
  }
}

// 初始化数据
const initData = async () => {
  try {
    // 并行加载数据
    await Promise.all([
      todosStore.fetchTodoLists(),
      todosStore.fetchTodos({ limit: 10 }),
      algorithmsStore.fetchProblems({ limit: 1 }),
      calendarStore.fetchEvents()
    ])
  } catch (error) {
    console.error('Failed to load dashboard data:', error)
  }
}

// 组件挂载时初始化数据
onMounted(() => {
  initData()
})
</script>

<style scoped>
.dashboard {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
}

.dashboard-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 8px 0;
}

.page-subtitle {
  font-size: 16px;
  color: #6b7280;
  margin: 0;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
}

.stat-card {
  border-radius: 12px;
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  background: rgba(32, 128, 240, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #6b7280;
  margin-top: 4px;
}

.dashboard-content {
  display: grid;
  grid-template-columns: 1fr 400px;
  gap: 24px;
}

.left-section,
.right-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.calendar-card,
.events-card,
.quick-add-card,
.todos-card,
.upcoming-card {
  border-radius: 12px;
}

.calendar-container {
  display: flex;
  justify-content: center;
}

.events-list,
.todos-list,
.upcoming-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.event-item,
.todo-item,
.upcoming-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  border-radius: 8px;
  background: #f9fafb;
  transition: all 0.2s ease;
}

.event-item:hover,
.todo-item:hover,
.upcoming-item:hover {
  background: #f3f4f6;
}

.event-time {
  font-size: 12px;
  color: #6b7280;
  font-weight: 500;
  min-width: 60px;
}

.event-content,
.todo-content,
.upcoming-content {
  flex: 1;
}

.event-title,
.todo-title,
.upcoming-title {
  font-weight: 500;
  color: #1f2937;
  margin-bottom: 4px;
}

.event-description {
  font-size: 12px;
  color: #6b7280;
}

.todo-due-date {
  font-size: 12px;
  color: #6b7280;
  display: flex;
  align-items: center;
  gap: 4px;
}

.upcoming-date {
  font-size: 12px;
  color: #6b7280;
}

.todo-item.completed .todo-title {
  text-decoration: line-through;
  color: #9ca3af;
}

.event-actions {
  display: flex;
  gap: 4px;
}

.quick-add-form {
  margin-bottom: 0;
}

.empty-state {
  padding: 20px;
  text-align: center;
}

.color-picker {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.color-option {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  cursor: pointer;
  border: 2px solid transparent;
  transition: all 0.2s ease;
}

.color-option:hover {
  transform: scale(1.1);
}

.color-option.active {
  border-color: #1f2937;
  transform: scale(1.1);
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .dashboard-content {
    grid-template-columns: 1fr;
  }
  
  .right-section {
    order: -1;
  }
}

@media (max-width: 768px) {
  .dashboard {
    padding: 16px;
  }
  
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .page-title {
    font-size: 24px;
  }
}

@media (max-width: 480px) {
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .stat-content {
    gap: 12px;
  }
  
  .stat-icon {
    width: 40px;
    height: 40px;
  }
  
  .stat-value {
    font-size: 20px;
  }
}
</style>